package com.ysd.lis.service.eq.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.eq.EqEquipment;
import com.ysd.lis.entity.eq.EqMaintainPlan;
import com.ysd.lis.entity.eq.EqMaintainPlanDetail;
import com.ysd.lis.entity.eq.EqMaintainPlanPerson;
import com.ysd.lis.mapper.eq.EqMaintainPlanDetailMapper;
import com.ysd.lis.mapper.eq.EqMaintainPlanMapper;
import com.ysd.lis.mapper.eq.EqMaintainPlanPersonMapper;
import com.ysd.lis.request.CommonPageDto;
import com.ysd.lis.request.eq.EqMaintainDto;
import com.ysd.lis.service.SysRuleSetService;
import com.ysd.lis.service.eq.EqMaintainPlanDetailService;
import com.ysd.lis.service.eq.EqMaintainPlanPersonService;
import com.ysd.lis.service.eq.EqMaintainPlanService;
import com.ysd.util.ToolsUtils;
import org.quartz.CronExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备管理-设备类型 服务实现类
 * </p>
 *
 * @author prs
 * @since 2024-08-16
 */
@Service("eqMaintainPlanService")
public class EqMaintainPlanServiceImpl extends ServiceImpl<EqMaintainPlanMapper, EqMaintainPlan> implements EqMaintainPlanService {

    @Autowired
    EqMaintainPlanMapper eqMaintainPlanMapper;
    @Autowired
    EqMaintainPlanPersonMapper eqMaintainPlanPersonMapper;
    @Autowired
    EqMaintainPlanPersonService eqMaintainPlanPersonService;
    @Autowired
    EqMaintainPlanDetailMapper eqMaintainPlanDetailMapper;
    @Autowired
    EqMaintainPlanDetailService eqMaintainPlanDetailService;
    @Autowired
    SysRuleSetService sysRuleSetService;//编码规则服务
    @Override
    public Result findMaintainPlanPageList(CommonPageDto pageParam) {
        Page<EqMaintainPlan> page = new Page<>();
        page.setCurrent(pageParam.getPageIndex());
        page.setSize(pageParam.getPageSize());
        MPJLambdaWrapper<EqMaintainPlan> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(EqMaintainPlan.class)
                .selectAs("eq", EqEquipment::getEquiptName,EqMaintainPlan::getEquiptName)
                .selectAs("eq",EqEquipment::getSpecification,EqMaintainPlan::getSpecification)
                .leftJoin(EqEquipment.class,"eq",EqEquipment::getId,EqMaintainPlan::getEquiptId)
                .eq(EqMaintainPlan::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(EqMaintainPlan::getPlanNo, pageParam.getSeachValue())
                    .or().like(EqMaintainPlan::getEquiptCode, pageParam.getSeachValue()));
        }

        if(ToolsUtils.isNotEmpty(pageParam.getStatus())){
            lambdaQueryWrapper.eq(EqMaintainPlan::getPlanStatus,pageParam.getStatus());
        }
        lambdaQueryWrapper.orderByDesc(EqMaintainPlan::getCreateTime);
        Page<EqMaintainPlan> planPage = eqMaintainPlanMapper.selectPage(page, lambdaQueryWrapper);
        return Result.succ(1, "查询成功", planPage);
    }

    @Override
    public Result batchDeleteMaintainPlanList(EqMaintainDto dto) {
        List<EqMaintainPlan> eqMaintainPlanList = dto.getEqMaintainPlanList();
        List<String> ids = eqMaintainPlanList.stream().map(EqMaintainPlan::getId).collect(Collectors.toList());
        boolean b = this.removeByIds(ids);
        if(b){
            //person
            LambdaUpdateWrapper<EqMaintainPlanPerson> deleteTableWrapper = new LambdaUpdateWrapper<>();
            deleteTableWrapper.in(EqMaintainPlanPerson::getPlanId, ids);
            eqMaintainPlanPersonMapper.delete(deleteTableWrapper);
            //Detail
            LambdaUpdateWrapper<EqMaintainPlanDetail> deleteSelectWrapper = new LambdaUpdateWrapper<>();
            deleteSelectWrapper.in(EqMaintainPlanDetail::getPlanId, ids);
            eqMaintainPlanDetailMapper.delete(deleteSelectWrapper);
            return Result.succ(1, "删除成功", null);
        }else {
            return Result.fail(400,"删除失败","");
        }
    }

    @Override
    public Result findEqMaintainPlanById(EqMaintainPlan eqMaintainPlan) {
        String id = eqMaintainPlan.getId();

        MPJLambdaWrapper<EqMaintainPlan> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(EqMaintainPlan.class)
                .selectAs("eq",EqEquipment::getEquiptName,EqMaintainPlan::getEquiptName)
                .selectAs("eq",EqEquipment::getSpecification,EqMaintainPlan::getSpecification)
                .leftJoin(EqEquipment.class,"eq",EqEquipment::getId,EqMaintainPlan::getEquiptId)
                .eq(EqMaintainPlan::getId,id)
                .eq(EqMaintainPlan::getDelFlag, 0);
        EqMaintainPlan maintainPlan = eqMaintainPlanMapper.selectOne(lambdaQueryWrapper);

        //获取person
        MPJLambdaWrapper<EqMaintainPlanPerson> queryTableWrapper = new MPJLambdaWrapper<>();
        queryTableWrapper.selectAll(EqMaintainPlanPerson.class)
                .eq(EqMaintainPlanPerson::getPlanId,id)
                .eq(EqMaintainPlanPerson::getDelFlag,0);
        List<EqMaintainPlanPerson> personList = eqMaintainPlanPersonMapper.selectList(queryTableWrapper);
        maintainPlan.setMaintainPlanPersonList(personList);
        //获取detail
        MPJLambdaWrapper<EqMaintainPlanDetail> queryTableWrapper1 = new MPJLambdaWrapper<>();
        queryTableWrapper1.selectAll(EqMaintainPlanDetail.class)
                .eq(EqMaintainPlanDetail::getPlanId,id)
                .eq(EqMaintainPlanDetail::getDelFlag,0);
        List<EqMaintainPlanDetail> detailList = eqMaintainPlanDetailMapper.selectList(queryTableWrapper1);
        maintainPlan.setMaintainPlanDetailList(detailList);

        return Result.succ(1, "查询成功", maintainPlan);
    }

    @Override
    public Result addMaintainPlan(EqMaintainPlan eqMaintainPlan) {
        String a = sysRuleSetService.createRuleCodeList("eqMaintainPlanNo", 1).get(0);
        eqMaintainPlan.setPlanNo(a);
        String planType = eqMaintainPlan.getPlanType();
        if(planType.equals("2")){
            try {
                CronExpression cronExpression = new CronExpression(eqMaintainPlan.getCron());
                Date nextInvalidTimeAfter = cronExpression.getNextValidTimeAfter(eqMaintainPlan.getStartDate());
                eqMaintainPlan.setNextDate(new Timestamp(nextInvalidTimeAfter.getTime()));
            } catch (Exception e) {
                Result.fail(400, "表达式不正确，请核实！", "");
            }
        }
        boolean save = this.save(eqMaintainPlan);
        if (save) {
            //person
            List<EqMaintainPlanPerson> maintainPlanPersonList = eqMaintainPlan.getMaintainPlanPersonList();
            for(EqMaintainPlanPerson maintainPlanPerson : maintainPlanPersonList){
                maintainPlanPerson.setPlanId(eqMaintainPlan.getId());
                maintainPlanPerson.setPlanNo(eqMaintainPlan.getPlanNo());
            }
            boolean b = eqMaintainPlanPersonService.saveBatch(maintainPlanPersonList);

            //detail
            List<EqMaintainPlanDetail> maintainPlanDetailList = eqMaintainPlan.getMaintainPlanDetailList();
            for(EqMaintainPlanDetail maintainPlanDetail : maintainPlanDetailList){
                maintainPlanDetail.setPlanId(eqMaintainPlan.getId());
                maintainPlanDetail.setPlanNo(eqMaintainPlan.getPlanNo());
            }
            boolean b1 = eqMaintainPlanDetailService.saveBatch(maintainPlanDetailList);
            return Result.succ(1, "添加成功", eqMaintainPlan);

        } else {
            return Result.fail("添加失败");
        }
    }

    @Override
    public Result updateMaintainPlan(EqMaintainPlan eqMaintainPlan) {
        String planType = eqMaintainPlan.getPlanType();
        if(planType.equals("2")){
            try {
                Timestamp startDate = eqMaintainPlan.getStartDate();
                int compare = DateUtil.compare(startDate, new Date());
                Date validTime = null;
                if (compare > 0) {
                    validTime = startDate;
                } else {
                    validTime = new Date();
                }

                CronExpression cronExpression = new CronExpression(eqMaintainPlan.getCron());
                Date nextInvalidTimeAfter = cronExpression.getNextValidTimeAfter(validTime);
                eqMaintainPlan.setNextDate(new Timestamp(nextInvalidTimeAfter.getTime()));
            } catch (Exception e) {
                Result.fail(400, "表达式不正确，请核实！", "");
            }
        }
        boolean save = this.updateById(eqMaintainPlan);
        if (save) {
            //person
            //先删除 再添加或修改
            LambdaQueryWrapper<EqMaintainPlanPerson> delPersonWrapper = new LambdaQueryWrapper<>();
            delPersonWrapper.eq(EqMaintainPlanPerson::getPlanId,eqMaintainPlan.getId());
            eqMaintainPlanPersonMapper.delete(delPersonWrapper);
            List<EqMaintainPlanPerson> eqMaintainPlanPersonList = eqMaintainPlan.getMaintainPlanPersonList();
            boolean b = eqMaintainPlanPersonService.saveBatch(eqMaintainPlanPersonList);

            //Detail
            //先删除 再添加或修改
            LambdaQueryWrapper<EqMaintainPlanDetail> delDetailWrapper = new LambdaQueryWrapper<>();
            delDetailWrapper.eq(EqMaintainPlanDetail::getPlanId,eqMaintainPlan.getId());
            eqMaintainPlanDetailMapper.delete(delDetailWrapper);
            List<EqMaintainPlanDetail> eqMaintainPlanDetailList = eqMaintainPlan.getMaintainPlanDetailList();
            boolean c = eqMaintainPlanDetailService.saveBatch(eqMaintainPlanDetailList);
            return Result.succ(1, "编辑成功", eqMaintainPlan);

        }else {
            return Result.fail("编辑失败");
        }
    }

    @Override
    public Result batchMaintainPlanStopStart(EqMaintainDto dto) {
        List<EqMaintainPlan> eqMaintainPlanList = dto.getEqMaintainPlanList();
        String planStatus = dto.getPlanStatus();
        eqMaintainPlanList.forEach(m->{
            m.setPlanStatus(planStatus);
        });
        boolean b = this.updateBatchById(eqMaintainPlanList);
        if (b){
            return Result.succ(1, "修改成功", null);
        } else {
            return Result.fail("添加失败");
        }
    }
}
